<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * FreakAuth_light Class to handle the front controller
 * this class make code more reusable and it makes easier to
 * integrate Freakauth_light in your on templating system
 *
 * The class requires the use of
 *
 * => Database CI official library
 * => Db_session library (included in the download)
 * => FAL_validation library (included in the download)
 * => Freakauth_light library (included in the download)
 * => URL, FORM and FreakAuth_light (included in the download) helpers
 *
 * -----------------------------------------------------------------------------
 * Copyright (C) 2009 TechPundits (tech-pundits.com)
 * -----------------------------------------------------------------------------
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 *------------------------------------------------------------------------------
 * @package     care and comfort 2009-09-18
 * @subpackage  Libraries
 * @category    Authentication
 * @author      pradeep kumar
 * @copyright   Copyright (c) 2009,TechPundits (tech-pundits.com)
 * @license		http://www.gnu.org/licenses/lgpl.html
 * @link 		http://tech-pundits.com
 * 
 *
 */

class CNC_services{
	
	
	function CNC_services()
	{
		
		$this->CI = &get_instance();
		//loads necessary libraries
        $this->CI->lang->load('freakauth');
        if (!class_exists('CI_Validation'))
		{
		     $this->CI->load->library('validation');
		}
		//let's load the FAL_validation library if it isn't already loaded
		if (!class_exists('FAL_validation'))
		{
		     $this->CI->load->library('FAL_validation');
		}
		
		//let's load the Freakauth_light library if it isn't already loaded
		//or autoloaded
		if (!class_exists('Freakauth_light'))
		{
		     $this->CI->load->library('Freakauth_light', 'freakauth_light');
		}
       
		//let's check if we have core classes extensions, and if we have them
		//let's load them
    	if ($this->CI->config->item('FAL_use_extensions'))
    	{
    	    $this->_loadExtensions();
    	}
    	else
    	{
    	    log_message('debug', 'FAL not using extensions');
    	}
       
		$this->CI->fal_validation->set_error_delimiters($this->CI->config->item('FAL_error_delimiter_open'), $this->CI->config->item('FAL_error_delimiter_close'));
		$this->_prefix = $this->CI->config->item('FAL_table_prefix');
        $this->_table = $this->_prefix.'grocery_order';       
	}
	
	 // --------------------------------------------------------------------
    /**
     * FAL extensions handler.
     * It makes easier to load extensions to the classes in 
     * (libraries/FreakAuth_light.php) or the FAL_validation.php class build
     *  your files according to the following specifications about file-names.
     *  You can place them either in system/libraries or in application/libraries
     * 
     * - libraries/MyFAL.php
     * - libraries/MyFALVal.php
     * 
     * Following this convention, if $config['FAL_use_extensions'] = TRUE;
     * the above files will be loaded 
     */
    function _loadExtensions()
    {
  
        if (file_exists(APPPATH.'libraries/MyFAL'.EXT) OR file_exists(BASEPATH.'libraries/MyFAL'.EXT))
        {
            //let's load the core library (i.e. FreakAuth_light.php) extension
            $this->CI->load->library('MyFAL');
            
            $this->CI->freakauth_light = new MyFAL();
            log_message('debug', 'MyFAL library loaded');
            log_message('debug', 'MyFAL class assigned to $this->CI->freakauth_light');
        }
        else
        {
            log_message('debug', 'MyFAL class not found');
        }

        if (file_exists(APPPATH.'libraries/MyFALVal'.EXT) OR file_exists(BASEPATH.'libraries/MyFALVal'.EXT))
        {
            //let's load the validation library (i.e. FAL_validation.php) extension
            //and assign it to $this->CI->fal_validation
            $this->CI->load->library('MyFALVal');
            $this->CI->fal_validation = new MyFALVal();

        }
        else
        {
            log_message('debug', 'MyFALVal class not found');
        }
    }
	function selectorders()
	{
		 $this->CI->load->helper('date');
		 $this->CI->load->model('Selectorders','selectorders');
		 $date = $this->CI->input->post('date');
		  
		 if($date!="")
		 {
		$search_res = $this->CI->selectorders->searchbydate($date);
		// $data['page']=$search_res;
		 }
        else
        {
         $data = array();
        }
		  $data = array('search_results'	=> (isset($search_res)) ? $search_res : '' ,
		  );
		  return $this->CI->load->view($this->CI->config->item('CNC_orders_view'), $data, TRUE);
	}
	
	
    function grocery($id)
    {
    	$values = $this->_get_csv_form_values();
    	
    	if($values['userid']!='')
    	{
    		//print_r($values);
    		
    		$this->upload_csv($id);
    	}
    	$this->CI->load->model('Services_model','services_model');
        $query = $this->CI->services_model->getGrocery($id);
   
        if ($query->num_rows()>0)
		{ 
			 $data['grocery']=$query->result();
		}
		$data['options']=array("" =>"Schedule",
		                       "weekly" =>"Every Week",
		                       "monthly"=>"Every Month",
		                       "15 days"    => "Every 15 Days");
		$username = ' for "'.getUserNameById($id).'"';
		if(isAdmin()){
    	$data['action']="Manage Grocery".$username;
		 } else
		$data['action']="Manage Grocery"; 
		
    	$data['controller']="admin/services";
    	$data['id'] = $id;
        $data['heading'] = "Grocery";
    	return $this->CI->load->view($this->CI->config->item('CNC_grocery_view'), $data, TRUE);
    	
    }
    
    // get service types plumber ,carpenter,Elect,Repairs
    function get_service_type1($type)
    {
    	$this->CI->load->model('Orders_model','orders_model');
    	$this->CI->load->helper('date');
    	 $fields['details'] = "Details";
    	
    	 $rules['details'] = 'trim|required';
    	 $fields['date'] = "Date";
    	 $rules['date'] = 'trim|required';
    	 $this->CI->fal_validation->set_fields($fields);
        $this->CI->fal_validation->set_rules($rules);
    switch($type)
        {
        	case 'plumber':
        		$form_action = 'services/plumber';
        		break;
        	case 'carpenter':
        		$form_action = 'services/carpenter';
        		break;
        	case 'electrician':
        		$form_action = 'services/electrician';
        		break;
        	case 'repairs':
        		$form_action = 'services/repairs';
        		break;	
        }
        if($this->CI->fal_validation->run())
        {
        	 $values['details'] = $this->CI->input->post('details');
        	 $values['date'] = $this->CI->input->post('date');
        	 $values['servicetype'] = $type;
        	 $values['order_date'] = now();
//			$time = time();
//			echo mdate($time);
        	 $values['userid'] = getUserId();
        	 $this->CI->orders_model->insertUserOrder($values);
        	 
        	switch ($type)
        	{
        		case 'plumber':
        			flashMsg('Plumber details sent to admin successfully');
        	        redirect($form_action,'location');
        	    case 'carpenter':
        			flashMsg('Carpenter details sent to admin successfully');
        	        redirect($form_action,'location');
        	     case 'electrician':
        			flashMsg('Electrician details sent to admin successfully');
        	        redirect($form_action,'location');
        	      case 'repairs':
        			flashMsg('Repairs details sent to admin successfully');
        	        redirect($form_action,'location');            
        	}
         }
        else
        {
         
        }
    	
//        $query = $this->CI->orders_model->getPlumber($id);
        $data['action'] = $this->CI->lang->line('CNC_manage_'.$type); 
    	$data['type'] = $type;
        $data['heading'] = "Plumber";
        $data['form_action'] = $form_action;
//      $data['query'] = $this->CI->orders_model->get_order_details($type,$limit=null,$offset=null);
    	return $this->CI->load->view($this->CI->config->item('CNC_plumber_view'), $data, TRUE);
    }
  
    function _get_csv_form_values()
    {
    	$values['userid'] = $this->CI->input->post('userid');
    	return $values;
    }
    
    function upload_csv($id)
    {
    	$config['upload_path'] = './'.$this->CI->config->item('FAL_assets_shared').'/'.$this->CI->config->item('CNC_csv').'/';
		$config['allowed_types'] = 'csv';
		$config['max_size']	= '5000';
		$this->CI->load->library('upload', $config);
      if ( ! $this->CI->upload->do_upload('file'))
		{
			$error = array('error' => $this->CI->upload->display_errors());
			flashMsg($error['error']);
			redirect('admin/services/grocery/'.$id);
		}	
		else
		{
			$data = array('upload_data' => $this->CI->upload->data());
			$this->insert_csv($data['upload_data'],$id);
			//flashMsg($data);
			redirect('admin/services/grocery/'.$id);
		}
    }
    
    function insert_csv($data,$userid)
    {
    	$path = './'.$this->CI->config->item('FAL_assets_shared').'/'.$this->CI->config->item('CNC_csv').'/';
    	$org_file_path = $path.$data['raw_name'].'.csv';
    	if(!file_exists($org_file_path))
    	{
    		echo "dsf";
    	}
    	else
    	{
    		$handle = fopen($org_file_path, 'r');
    		$count =0;
	      $grocery_tb_affected =0;
    		while(($data = fgetcsv($handle, 1000, ",")) !== false)
	      {
	      	$count++;
	      	if($count == 1)
	      	{
	      		continue;
	      	}
	      	
	      	$values['userid'] = $userid;
	      	$values['name'] = $data[0];
	      	$values['brand'] = $data[1];
	      	$values['quantity'] = $data[2];
	      	$values['date']	= $data[3];
	      	$values['schedule'] = $data[4];
	       
	      
	      	$this->CI->db->insert($this->_table, $values);
	      	$grocery_tb_affected = $grocery_tb_affected + $this->CI->db->affected_rows();
//	      $query = "insert into grocery_order(userid,name,brand,quantity,date,schedule)
//						values($userid,'$data[0]','$data[1]','$data[2]','$data[3]','$data[4]')";
//			if(!mysql_query($query))
//			{
//			
//			}
	      }
	      //$user_tb_affected = $this->CI->db->affected_rows();
	      flashMsg($grocery_tb_affected.' items inserted successfully');
      		fclose($handle);
      	 	unlink($org_file_path);
    	}
    	
    	$this->CI->load->helper('date');
    	  
    	
    }
    
    
}